package com.kundi.dooradmin.controller;

import com.kundi.dooradmin.entity.User;
import com.kundi.dooradmin.service.UserService;
import com.kundi.dooradmin.util.MapUtil;
import com.kundi.dooradmin.util.Md5Util;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    UserService userService;

    /**
     * 用户登录验证
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("/login")
    @ResponseBody
    public Map<String, String> login(String username, String password) {
        return userService.login(username, password);
    }

    /**
     * 用户修改个人信息
     * @param user
     * @return
     */
    @RequestMapping("/update")
    @ResponseBody
    public Map<String, String> update(User user) {
        user.setId(userService.getIdByUsername(user.getUsername()));
        System.out.println(user);
        Map<String, String> map = new HashMap<>();
        Integer i  = userService.update(user);
        if(i > 0) {
            map.put("message", "修改成功");
            map.put("success", "true");
        } else {
            map.put("message", "修改失败");
            map.put("success", "false");
        }
        return map;
    }

    /**
     * 根据用户名获取用户信息
     * @param username
     * @return
     */
    @RequestMapping("{username}")
    public User getUserByUsername(@PathVariable String username) {
        return userService.getUserById(userService.getIdByUsername(username));
    }

    /**
     * 获取所有的用户信息
     * @return
     */
    @GetMapping("/")
    @ResponseBody
    public List<User> getAll() {
        return userService.getAllUser();
    }

    /**
     * 新用户注册
     * @param user
     * @return
     */
    @PostMapping("/")
    @ResponseBody
    public Map<String, String> insert(User user) {
        System.out.println(user);
        // 对密码进行MD5加密，防止被破解，且后台管理员也不会知道用户的密码
        user.setPassword(Md5Util.getMD5Upper(user.getPassword()));
        User user1 = userService.insert(user);
        if (user1 != null) {
            return MapUtil.responseMap("注册成功", "true");
        } else {
            return MapUtil.responseMap("注册失败", "false");
        }
    }
}
